﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using BCService;
using BCService.Chats;

namespace BCTMSRESTful.Configs
{
    public class WebSocketContextService : IWebSocketContextService
    {
        private readonly static ConcurrentDictionary<string, ConcurrentDictionary<string, (WebSocket WebSocket, CancellationToken CancellationToken)>> SavedWebSockets = new ConcurrentDictionary<string, ConcurrentDictionary<string, (WebSocket, CancellationToken)>>();
        private readonly static string LogFile = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}WebSocket.log";
        private readonly int BufferSize = 4096;

        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IApplicationContextService applicationContextService;

        private string currentSecWebSocketKey;
        private string currentChatUserId;
        private WebSocket currentWebSocket;
        private CancellationToken? currentCancellationToken;

        private bool disposed = false;

        public event Action OnConnected;
        public event Action<string> OnTextReceived;
        public event Action<byte[]> OnBinaryReceived;
        public event Action OnClosed;

        public WebSocketContextService(IConfiguration configuration,
            IHttpContextAccessor httpContextAccessor,
            IApplicationContextService applicationContextService)
        {
            if (int.TryParse(configuration["WebSocket:BufferSize"], out var value))
            {
                this.BufferSize = value;
            }

            this.httpContextAccessor = httpContextAccessor;
            this.applicationContextService = applicationContextService;
        }

        public async Task TryListenAsync()
        {
            await this.AcceptWebSocketAsync();

            var seg = new ArraySegment<byte>(new byte[this.BufferSize]);
            var receivedBytes = new List<byte>();

            while (!this.disposed && this.currentWebSocket?.State == WebSocketState.Open)
            {
                try
                {
                    var incoming = await this.currentWebSocket.ReceiveAsync(seg, this.currentCancellationToken.Value);

                    receivedBytes.AddRange(seg.Array.Take(incoming.Count));

                    if (!incoming.EndOfMessage)
                    {
                        continue;
                    }
                    if (incoming.MessageType == WebSocketMessageType.Text)
                    {
                        this.OnTextReceived?.Invoke(Encoding.UTF8.GetString(receivedBytes.ToArray()));
                    }

                    if (incoming.MessageType == WebSocketMessageType.Binary)
                    {
                        this.OnBinaryReceived?.Invoke(receivedBytes.ToArray());
                    }

                    if (incoming.MessageType == WebSocketMessageType.Close)
                    {
                        await this.currentWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "客服端关闭。", this.currentCancellationToken.Value);

                        break;
                    }

                    receivedBytes = new List<byte>();
                }
                catch (Exception ex)
                {
#if DEBUG
                    Console.WriteLine("WebSocket 异常:");
                    Console.WriteLine(ex);
#endif
                    if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.EndpointUnavailable) {
                        await this.TryCloseAsync(WebSocketCloseStatus.EndpointUnavailable, "客户端浏览器关闭了");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.ProtocolError)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "协议错误，关闭此链接");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.InvalidMessageType)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "发送的数据并不被服务器接受，关闭此链接");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.InvalidPayloadData)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "收到的消息数据无效，关闭此链接");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.MessageTooBig)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "此消息传输数据过大，关闭此链接");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.PolicyViolation)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "此消息违反策略，关闭此链接");
                    }
                    else if (this.currentWebSocket.CloseStatus.HasValue && this.currentWebSocket.CloseStatus.Value == WebSocketCloseStatus.InternalServerError)
                    {
                        await this.TryCloseAsync(WebSocketCloseStatus.ProtocolError, "服务器内部错误，关闭此链接");
                    }
                    this.WriteLogAsync(ex.ToString());
                }

#if DEBUG
                Console.WriteLine($"WebSocket 现在的连接状态是 {this.currentWebSocket?.State}");
#endif
            }
        }

        public async Task TryCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
        {
            if (this.disposed)
            {
                return;
            }

            this.disposed = true;

            // 以下任意项为空，都意味着 WebSocket 压根没有初始化。
            if (string.IsNullOrWhiteSpace(this.currentSecWebSocketKey) || string.IsNullOrWhiteSpace(this.currentChatUserId) || this.currentWebSocket == null)
            {
                return;
            }

            if (this.currentWebSocket != null)
            {
                try
                {
                    if (this.currentWebSocket?.State == WebSocketState.Open)
                    {
                        await this.currentWebSocket.CloseAsync(closeStatus, statusDescription, this.currentCancellationToken.Value);
                    }

                    this.currentWebSocket.Abort();
                    this.currentWebSocket.Dispose();
                }
                catch (Exception ex)
                {
                    this.WriteLogAsync(ex.ToString());
                }
            }

            if (SavedWebSockets.TryGetValue(this.currentChatUserId, out var currentUserWebSocketCollection))
            {
                currentUserWebSocketCollection.TryRemove(this.currentSecWebSocketKey, out var _);

                if (currentUserWebSocketCollection.Count == 0)
                {
                    SavedWebSockets.TryRemove(this.currentChatUserId, out var _);
                }
            }

            this.OnClosed?.Invoke();
        }

        public async Task<bool> SendTextAsync(string text, string chatUserId = null)
        {
            return await this.SendInternalAsync(WebSocketMessageType.Text, Encoding.UTF8.GetBytes(text), chatUserId ?? this.currentChatUserId);
        }

        public async Task<bool> SendBinaryAsync(byte[] bytes, string chatUserId = null)
        {
            return await this.SendInternalAsync(WebSocketMessageType.Binary, bytes, chatUserId ?? this.currentChatUserId);
        }

        public Task<bool> CheckOnlineAsync(string chatUserId)
        {
            if (SavedWebSockets.TryGetValue(chatUserId, out var results) && results.Count > 0)
            {
                return Task.FromResult(true);
            }

            return Task.FromResult(false);
        }

        public async void Dispose()
        {
            await this.TryCloseAsync(WebSocketCloseStatus.Empty, null);
        }

        private async Task AcceptWebSocketAsync()
        {
            if (httpContextAccessor.HttpContext == null)
            {
                throw new ArgumentNullException("当前不是 WebSocket 请求，无法创建 WebSocket 连接。");
            }

            if (httpContextAccessor.HttpContext.WebSockets?.IsWebSocketRequest != true)
            {
                await httpContextAccessor.HttpContext.Response.WriteAsync(StatusCodes.Status400BadRequest, "当前不是 WebSocket 请求，无法创建 WebSocket 连接。");

                return;
            }

            this.currentSecWebSocketKey = httpContextAccessor.HttpContext.Request.Headers["Sec-WebSocket-Key"].ToString();

            if (string.IsNullOrWhiteSpace(this.currentSecWebSocketKey))
            {
                await httpContextAccessor.HttpContext.Response.WriteAsync(StatusCodes.Status400BadRequest, "缺少必要的 WebSocket 参数，无法创建连接。");

                return;
            }

            if (!httpContextAccessor.HttpContext.Request.Query.ContainsKey("token"))
            {
                await httpContextAccessor.HttpContext.Response.WriteAsync(StatusCodes.Status400BadRequest, "缺少 Token 参数，无法创建连接。");

                return;
            }

            try
            {
                this.currentChatUserId = applicationContextService.GetChatUserId();
            }
            catch
            {
                await httpContextAccessor.HttpContext.Response.WriteAsync(StatusCodes.Status401Unauthorized, "传入的 Token 无效或者已过期，无法创建连接。");

                return;
            }

            try
            {
                this.currentWebSocket = await httpContextAccessor.HttpContext.WebSockets.AcceptWebSocketAsync();
                this.currentCancellationToken = httpContextAccessor.HttpContext.RequestAborted;

                if (!SavedWebSockets.ContainsKey(this.currentChatUserId))
                {
                    if (!SavedWebSockets.TryAdd(this.currentChatUserId, new ConcurrentDictionary<string, (WebSocket, CancellationToken)>()))
                    {
                        throw new Exception("初始化 WebSocket 环境失败，无法创建连接。");
                    }
                }

                if (!SavedWebSockets[this.currentChatUserId].TryAdd(this.currentSecWebSocketKey, (this.currentWebSocket, this.currentCancellationToken.Value)))
                {
                    throw new Exception("无法保存 WebSocket 连接，服务器已主动关闭连接。");
                }
            }
            catch (Exception ex)
            {
                if (this.currentWebSocket?.State == WebSocketState.Open)
                {
                    await this.currentWebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, ex.Message, this.currentCancellationToken.Value);
                }
            }

            this.OnConnected?.Invoke();
        }

        private async Task<bool> SendInternalAsync(WebSocketMessageType messageType, byte[] bytes, string chatUserId)
        {
            if (!SavedWebSockets.TryGetValue(chatUserId, out var currentUserWebSocketCollection))
            {
                return false;
            }

            bool success = false;

            try
            {
                foreach (var (webSocket, cancellationToken) in currentUserWebSocketCollection.Values)
                {
                    for (int i = 0, offset = 0; offset < bytes.Length; i++, offset = this.BufferSize * i)
                    {
                        if (bytes.Length - offset > this.BufferSize)
                        {
                            var outgoing = new ArraySegment<byte>(bytes, offset, this.BufferSize);

                            await webSocket.SendAsync(outgoing, messageType, false, cancellationToken);
                        }
                        else
                        {
                            var outgoing = new ArraySegment<byte>(bytes, offset, bytes.Length - offset);

                            await webSocket.SendAsync(outgoing, messageType, true, cancellationToken);
                        }
                    }

                    success = true;
                }
            }
            catch (Exception ex)
            {
                this.WriteLogAsync(ex.ToString());
            }

            return success;
        }

        private void WriteLogAsync(string message)
        {
            File.AppendAllTextAsync(LogFile, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]{message}{Environment.NewLine}{Environment.NewLine}");
        }
    }
}